1877E - Autosynthesis - CodeForces Solution


constructive algorithms graphs

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define yes cout<<"YES"<<endl;
#define endl "\n"
const int N=2e5+10;
const int mod=998244353;
const ll inf=0x3f3f3f3f3f3f3f3f;

int a[N],vis[N],tag[N];
int flag=1,cnt=0;

void dfs(int u)
{
	if(tag[a[u]])
	{
		if(tag[a[u]]!=3-tag[u])
		{
			flag=0;
		}
		return ;
	}
	else
	{
		tag[a[u]]=3-tag[u];
		dfs(a[u]);
	}
}

void solve()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		vis[a[i]]++;
	}
	queue<int>q;
	for(int i=1;i<=n;i++)
	{
		if(!vis[i])
		{
			q.push(i);
			//cout<<i<<endl;
		}
	}
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		tag[u]=1;
		if(!tag[a[u]]&&--vis[a[a[u]]]==0)
		{
			q.push(a[a[u]]);
		}
		tag[a[u]]=2;
	}
	for(int i=1;i<=n;i++)
	{
		//cout<<tag[i]<<" \n"[i==n];
		if(!tag[i])tag[i]=1,dfs(i);
	}
	if(!flag)
	{
		cout<<"-1\n";
	}
	else
	{
		vector<int>ans;
		for(int i=1;i<=n;i++)
		{
			if(tag[i]==1)
			{
				ans.push_back(i);
			}
		}
		cout<<(int)ans.size()<<"\n";
		for(int i:ans)
		{
			cout<<a[i]<<" ";
		}
		cout<<"\n";
	}
}

int main()
{
	ios::sync_with_stdio(0);cin.tie(0);
	int _=1;
	//cin>>_;
	while(_--)
	{
		solve();
	}
}


Comments

Submit
0 Comments
More Questions

492A - Vanya and Cubes
217A - Ice Skating
270A - Fancy Fence
181A - Series of Crimes
1638A - Reverse
1654C - Alice and the Cake
369A - Valera and Plates
1626A - Equidistant Letters
977D - Divide by three multiply by two
1654B - Prefix Removals
1654A - Maximum Cake Tastiness
1649A - Game
139A - Petr and Book
1612A - Distance
520A - Pangram
124A - The number of positions
1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro
780C - Andryusha and Colored Balloons